<script setup lang="ts">
import { getArticleDetailAPI, publishAPI, updateArticleAPI, uploadAPI } from '@/apis/publish'
import GeekChannel from '@/components/geek-channel.vue'
import router from '@/router'
import type { PublishArticleResponse } from '@/types/publish'
import { ArrowRight, Plus } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type UploadRequestOptions } from 'element-plus'
import { ref } from 'vue'
import { useRoute } from 'vue-router'

const articleForm = ref<PublishArticleResponse>({
  title: '',
  content: '',
  cover: {
    type: 1,
    images: [],
  },
  channel_id: null,
})

const imageRuls = (
  rule: PublishArticleResponse['cover'],
  value: PublishArticleResponse['cover'],
  callback: (error?: Error) => void,
) => {
  if (value.type === 1 && value.images.length === 0) {
    return callback(new Error('请上传一张图片'))
  } else if (value.type === 3 && value.images.length === 0) {
    return callback(new Error('请上传三张图片'))
  } else {
    return callback()
  }
}

const articleRules = ref({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 4, max: 10, message: '文章标题4-50字符', trigger: 'blur' },
  ],
  channel_id: [{ required: true, message: '请选择频道', trigger: 'change' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  cover: [{ validator: imageRuls, trigger: 'change' }],
})

// 图片上传
const upload = ref<FormInstance>()
const fromRef = ref<FormInstance>()
const FileListImg = ref<UploadRequestOptions[]>([])
const uploadFile = async (options: UploadRequestOptions) => {
  const fd = new FormData()
  fd.append('image', options.file)
  const res = await uploadAPI(fd)
  articleForm.value.cover.images.push(res.data.url)
  // 校验图片
  fromRef.value?.validateField('cover')
  return res.data.url
}

// 删除上传文件
const removeUpload = (file: UploadRequestOptions) => {
  articleForm.value.cover.images = []
  FileListImg.value = FileListImg.value.filter((item) => item.file !== file.file)
  fromRef.value?.validateField('cover')
}

// 封面类型切换
const changeCoverType = () => {
  // 清空图片
  upload.value?.clearValidate()
  articleForm.value.cover.images = []
  fromRef.value?.validateField('cover')
}

// 发布文章
const Draft = ref<boolean>(false)
const route = useRoute()
const onsubmit = async (flag: boolean) => {
  if (route.params.id) {
    await fromRef.value?.validate()
    Draft.value = flag
    await updateArticleAPI(route.params.id as string, articleForm.value, Draft.value)
    ElMessage.success(Draft.value ? '保存草稿成功' : '修改文章成功')
  } else {
    await fromRef.value?.validate()
    Draft.value = flag
    await publishAPI(articleForm.value, Draft.value)
    ElMessage.success('发布文章成功')
  }
  router.push('/article')
}

// 回显数据-获取文章详情
const getArticleDetail = async () => {
  const res = await getArticleDetailAPI(route.params.id as string)
  const { channel_id, content, cover, title } = res.data
  articleForm.value.channel_id = channel_id
  articleForm.value.content = content
  articleForm.value.cover = cover
  articleForm.value.title = title
  // 回显图片
  FileListImg.value = cover.images.map((item) => {
    return {
      url: item,
    }
  })
}

if (route.params.id) {
  getArticleDetail()
}
// 富文本编辑器失去焦点校验
const checkContent = () => {
  fromRef.value?.validateField('content')
}
</script>

<template>
  <el-card>
    <template #header>
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>

        <!-- 通过template编组,通过一个v-if控制对个标签的条件渲染 -->
        <template v-if="$route.params.id">
          <el-breadcrumb-item :to="{ path: '/article' }">内容管理</el-breadcrumb-item>
          <el-breadcrumb-item>修改文章</el-breadcrumb-item>
        </template>

        <el-breadcrumb-item v-else>发布文章</el-breadcrumb-item>
      </el-breadcrumb>
    </template>
    <!-- 表单数据 -->
    <el-form label-width="120px" :model="articleForm" :rules="articleRules" ref="fromRef">
      <el-form-item label="标题：" style="width: 450px" prop="title">
        <el-input placeholder="请输入标题" v-model="articleForm.title"></el-input>
      </el-form-item>

      <el-form-item label="频道：" prop="channel_id">
        <GeekChannel v-model="articleForm.channel_id" />
      </el-form-item>

      <el-form-item label="封面：" prop="cover">
        <el-radio-group v-model="articleForm.cover.type" @change="changeCoverType()">
          <el-radio :label="1">单图</el-radio>
          <el-radio :label="3">三图</el-radio>
          <el-radio :label="0">无图</el-radio>
          <el-radio :label="-1">自动</el-radio>
        </el-radio-group>

        <!-- 插入图片 -->
        <div v-if="articleForm.cover.type === 1 || articleForm.cover.type === 3">
          <el-upload
            ref="upload"
            action=""
            list-type="picture-card"
            :http-request="uploadFile"
            @remove="removeUpload"
            :limit="articleForm.cover.type"
            v-model:file-list="FileListImg"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>
      </el-form-item>

      <!-- 内容 -->
      <el-form-item label="内容：" prop="content">
        <QuillEditor
          theme="snow"
          v-model:content="articleForm.content"
          content-type="html"
          ref="quillEditor"
          @blur="checkContent()"
        ></QuillEditor>
      </el-form-item>

      <el-form-item v-if="$route.params.id">
        <el-button type="primary" @click="onsubmit(false)">修改文章</el-button>
        <el-button @click="onsubmit(true)">存入草稿</el-button>
      </el-form-item>

      <el-form-item v-else>
        <el-button type="primary" @click="onsubmit(false)">发布文章</el-button>
        <el-button @click="onsubmit(false)">存入草稿</el-button>
      </el-form-item>
    </el-form>
    {{ articleForm }}
  </el-card>
</template>

<style scoped>
/* 样式 */
::v-deep .el-form-item__content {
  display: block;
}
.el-button {
  margin-top: 50px;
}
::v-deep .ql-editor {
  min-height: 200px;
}
</style>
